var self = require("sdk/self");
var tabs = require("sdk/tabs");
const urls_strings = self.data.load("urls.json")
var urls_parsed = JSON.parse(urls_strings);




function getLocation(href) {
   let indexOf3rdSlash = href.indexOf("://");
   let afterProtocol =  href.substr(indexOf3rdSlash + 3);
   let indexOfPathStart =  (afterProtocol.indexOf("/") < 0) ? afterProtocol.indexOf("?"):afterProtocol.indexOf("/");
   let indexOfPath = indexOfPathStart + indexOf3rdSlash + 3;
   return href.substr(0, indexOfPath);
};

function getURL(originalUrl) {
   let host = getLocation(originalUrl);
   let path = originalUrl.substr(host.length);
   let redirectUrl =  host + ".nyud.net" + path; 
//   console.log("COREL_NEWS:" + originalUrl + " is  to be replaced with " + redirectUrl);
   return redirectUrl;
}

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

function isToBeReplaced(theUrl) {
  for (let i = 0; i < urls_parsed.length; i++) {
      if (theUrl.indexOf(urls_parsed[i]) == 0 && theUrl.length > urls_parsed[i].length) {
//         console.log("COREL_NEWS:" + theUrl + " starts with " + urls_parsed[i]);
         return true;
     }
    }
 
   return false;
}

const {Cc,Ci,Cr,Cu} = require("chrome");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");


var utils = require('sdk/window/utils');
Cc["@mozilla.org/observer-service;1"]
    .getService(Ci.nsIObserverService)
    .addObserver({
        observe: function(subject, topic, data) {
            var url = subject
                    .QueryInterface(Ci.nsIHttpChannel)
                    .originalURI.spec;
            if(isToBeReplaced(url)) {
                //stop
                let channel = subject.QueryInterface(Ci.nsIHttpChannel);
                channel.cancel(Cr.NS_BINDING_ABORTED);
//                console.log("original channel=" + channel + " canceled");

                let gBrowser = utils.getMostRecentBrowserWindow().gBrowser;
//                console.log("got gBrowser = " + gBrowser);
                let domWin = channel.notificationCallbacks.getInterface(Ci.nsIDOMWindow);
//                console.log("got domWin = " + domWin);
                let browser = gBrowser.getBrowserForDocument(domWin.top.document);
//                console.log("got browser = " + browser);
                //redirect
                let redirectToUrl = getURL(url);
                browser.loadURI(redirectToUrl);
//                console.log("browser=" + browser + " loaded uri=" + redirectToUrl);
            }
        }
    }, "http-on-modify-request", false);
    
